对于 Powershell 脚本的参数,我们可以通过一些属性来限制参数。
今天我们就来看看,怎么通过参数属性来限制某个参数的个数,限制某个参数的长度。
下面来看看今天的示例脚本:
function test-net_port {
[cmdletbinding()]
param(
[parameter(mandatory=$true,Helpmessage="Enter the name of a computer to check connectivity to.")]
[ValidateCount(1,5)] # 限制参数的个数,在 1 到 5 个之间(包括 5 个)
[ValidateLength(1,15)] # 单个参数的长度在 1 到 15 之间
[string[]]$computerName,
[parameter(mandatory=$false)]
[int] $port
)
foreach ($computer in $computerName) {
Write-Verbose "Now testing $computer."
if ($port -eq "")
{
$ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue
} else {
$ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue -Port $port
}
if ($ping){
Write-Output $ping
} else {
Write-Verbose "Ping failed on $computer. Check the network connection."
Write-Output $ping
}
}
}
在 ISE 下面运行:
PS C:\Users\> test-net_port -computerName www.bing.com
True
# 当单个参数的长度超过 15 时
PS C:\Users\> test-net_port -computerName www.opscoffee.com
test-net_port : Cannot validate argument on parameter 'computerName'. The character length of the 17 argument is too long. Shorten the character length of the argument so it is fewer than
or equal to "15" characters, and then try the command again.
At line:1 char:29
+ test-net_port -computerName www.opscoffee.com
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [test-net_port], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port
# 当参数个数超过 5 个时
PS C:\Users\> test-net_port www.bing.com,www.baidu.com,www.google.com,www.yahoo.com,www.bing.com,www.baidu.com
test-net_port : Cannot validate argument on parameter 'computerName'. The number of provided arguments, (6), exceeds the maximum number of allowed arguments (5). Provide fewer than 5
arguments, and then try the command again.
At line:1 char:15
+ ... st-net_port www.bing.com,www.baidu.com,www.google.com,www.yahoo.com,w ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [test-net_port], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port